<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>分类管理</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
  <link rel="stylesheet" href="../../static/css/me.css" th:href="@{/css/me.css}">
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.js"></script>

</head>
<body>
  <div id="types">
    <!--导航-->
    <nav class="ui inverted attached segment m-padded-tb-mini m-shadow-small" >
      <div class="ui container">
        <div class="ui inverted secondary stackable menu">
          <h2 class="ui olive header item" style="font-family: STSong; font-weight: 900" >管理后台</h2>
          <a href="/admin/blogs/index" class="m-item item m-mobile-hide"><i class="mini el-icon-tickets"></i>&nbsp博客管理</a>
          <a href="/admin/types/index" class="active m-item item m-mobile-hide"><i class="mini el-icon-s-opportunity"></i>&nbsp分类管理</a>
          <a href="/admin/tags/index" class="m-item item m-mobile-hide"><i class="mini el-icon-s-flag"></i>&nbsp标签管理</a>
          <div class="right m-item m-mobile-hide menu">
            <div class="ui dropdown  item">
              <div class="text">
                <img class="ui avatar image" src="https://unsplash.it/1000/400?image=1015">
                <p align="center" th:text="${session.user.username}">风中的人儿啊~</p>
              </div>
              <i class="dropdown icon"></i>
              <div class="menu">
                <a href="/admin/logout" th:href="@{/admin/logout}" class="item">注销</a>
              </div>
            </div>
            <div class="item">
              <el-button size="small" type="info" round @click="resetUserInfo()">修改个人信息</el-button>
            </div>
          </div>
        </div>
      </div>
    </nav>

    <!--发布、列表二级导航-->
    <div class="ui attached pointing menu">
      <div class="ui container">
        <div class="right menu">
          <div style="border-right:1px; border-left: 1px solid rgb(232, 233, 233);">
            <a href="#/type_input" @click="touchClassA" class="item" :class="isClassA ? ['active','teal'] : ''">发布</a>
          </div>
          <div style="border-right:1px">
            <a href="#/type_list" @click="touchClassB" class="item" :class="isClassB ? ['active','teal'] : ''" >列表</a>
          </div >
        </div>
      </div>
    </div>

    <!--中间内容-->
    <router-view></router-view>

    <!--用户信息编辑表单-->
    <div v-show="show" class=" m-border" style="float: right;margin-top: -350px; margin-right: 130px; width: 15%; padding-top: 20px; border: 2px solid #f2f2f2; border-radius: 5px" align="center">
      <el-form style="width: 90%" :model="userForm" :rules="rules" ref="userForm">
        <el-form-item label="" prop="newUserName">
          <el-input v-model="userForm.newUserName"
                    type="text" prefix-icon="el-icon-user"
                    clearable placeholder="新用户名" style=""></el-input>
        </el-form-item>
        <el-form-item label="" prop="newPassword">
          <el-input v-model="userForm.newPassword"
                    type="password"
                    prefix-icon="el-icon-lock" clearable
                    placeholder="新密码"></el-input>
        </el-form-item>
        <el-form-item label="" prop="oldPassword">
          <el-input v-model="userForm.oldPassword"
                    type="password"
                    prefix-icon="el-icon-lock" clearable
                    placeholder="原密码"
                    @keyup.enter.native="submitUserForm('userForm')"></el-input>
        </el-form-item>
        <el-form-item style="width: 70%">
          <el-button class="m-border" type="primary" @click="submitUserForm('userForm')" style="background-color: #00aaaa">提交</el-button>
          <el-button class="m-border" @click="getBack('userForm')" style="">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>

    <!--底部footer-->
    <footer class="ui inverted vertical segment m-padded-tb-massive">
      <div class="ui center aligned container">
        <div class="ui inverted divided stackable grid">
          <div class="three wide column">
            <div class="ui inverted link list">
              <div class="item">
                <img th:src="@{/images/wechat.jpg}" class="ui rounded image" alt="" style="width: 110px">
              </div>
            </div>
          </div>
          <div class="three wide column">
            <h4 class="ui inverted header m-text-thin m-text-spaced ">联系我</h4>
            <div class="ui inverted link list">
              <a href="#" class="item m-text-thin">Email：luosj@bff.com</a>
              <a href="#" class="item m-text-thin">QQ：2542331408</a>
            </div>
          </div>
          <div class="seven wide column">
            <h4 class="ui inverted header m-text-thin m-text-spaced ">Blog</h4>
            <p class="m-text-thin m-text-spaced m-opacity-mini">这是我的个人博客、会分享关于编程、写作、思考相关的任何内容，希望可以给来到这儿的人有所帮助...</p>
          </div>
        </div>
        <div class="ui inverted section divider"></div>
        <div style="color: #F08047;margin-top: -18px" class="ui inverted m-text-thin m-text-spaced">我的客栈已营业：<span id="htmer_time" class="item m-text-thin"></span> (*๓´╰╯`๓)</div>
        <p class="m-text-thin m-text-spaced m-opacity-tiny">Copyright © 2020 - 2021 Luosj Designed by Luosj</p>
      </div>
    </footer>
  </div>
</body>
</html>

<!-- 组建1: 添加视图 -->
<template id="typeInputTemplate" align="center">
  <div id="type_input" align="center">
    <div id="type_input_index" class="input_index">
      <el-form :model="typeForm" :rules="rules" ref="typeForm">
        <el-form-item prop="name">
          <el-input
                  clearable
                  placeholder="分类名称"
                  v-model="typeForm.name"
                  @keyup.enter.native="submitForm('typeForm')">
            <template slot="prepend">名称</template>
          </el-input>
        </el-form-item>
        <el-form-item style="margin-top: -8px;" align="right">
          <el-button class="m-border"
                     @click="toBackList()"
                     style="background-color: rgb(224, 225, 226);
                     font-weight: 700;">返回</el-button>
          <el-button class="m-border"
                     type="primary"
                     @click="submitForm('typeForm')"
                     style="background-color: #00aaaa;
                     font-weight: 700;">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<!-- 组件2: 列表视图 -->
<template id="typeListTemplate">
  <div id="type_list" align="center">
    <div id="type_list_index" class="list_index">
      <el-table
              :data="tableData"
              style="width: 100%"
              :header-cell-style="tableHeaderColor">
        <el-table-column
                label=""
                type="index"
                :index="indexMethod"
                width="180">
        </el-table-column>
        <el-table-column
                label="分类名称"
                width="240">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium" style="color:#000;">{{ scope.row.name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                    size="mini"
                    style="background-color: #67c23a; border-color: #67c23a; color: rgb(255,255,255)"
                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-popconfirm
                    confirm-button-text='是的'
                    cancel-button-text='不用了'
                    icon="el-icon-info"
                    icon-color="red"
                    title="确定要删除当前分类吗？"
                    @confirm="handleDelete(scope.$index, scope.row)"
            >
              <el-button size="mini"
                         type="danger"
                         slot="reference">删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="page_index">
        <div>
          <div style="float: left">
            <el-pagination
                    background
                    prev-text="上一页"
                    next-text="下一页"
                    layout="prev, pager, next,jumper,total,sizes"
                    :page-size="size"
                    :current-page="pageNow"
                    :page-sizes="[2,4,6,8,10]"
                    @current-change="findPage"
                    @size-change="findSize"
                    :total="total">
            </el-pagination>
          </div>
          <div style="float: right; margin-right: 7px">
            <el-button
                    size="mini"
                    style="background-color: #00aaaa; border-color: #00aaaa; color: rgb(255,255,255)"
                    @click="toCreateType()">新增</el-button>
          </div>
          <div style="clear: both"></div> <!--在 .head div 最后补一个空DIV 清除浮动-->
        </div>
      </div>
    </div>
  </div>
</template>

<script>

  //组件1 typeInput
  const typeInput = {
    template:"#typeInputTemplate",
    data(){
      return {
        typeForm:{
          id:-1,
          name:""
        },
        rules: {
          name: [
            { required: true, message: '分类名称不能为空', trigger: 'blur' }
          ]
        },
      };
    },
    methods:{
      // 返回按钮路由跳转
      toBackList(){
        this.$parent.touchClassB(); // 调用方法改变导航按钮样式
        this.$router.push({path:'/type_list'}) // 跳转路由
      },
      // 提交表单
      submitForm(typeForm) {
        const _this = this;
        this.$refs[typeForm].validate((valid) => {
          if (valid) {
            // 当 id == -1 即表示新创建分类
            if (this.typeForm.id == -1){
              //发送一个ajax请求
              axios.post("http://localhost:8088/admin/types/create", this.typeForm).then(res => {
                console.log(res.data);
                if (res.data.code == 0) { //添加成功
                  this.$message({
                    message: '分类添加成功',
                    type: 'success',
                    offset:120,
                    showClose:true
                  });
                  // 阻塞0.3秒
                  setTimeout(function() {
                    _this.toBackList(); // 返回至列表
                  }, 300);
                } else { // 添加失败
                  this.$message({
                    message:res.data.message,
                    type: 'error',
                    offset:120,
                    showClose:true
                  });
                }
              });
            } else {
              // 当 id ！= -1 即表示新更新分类
              // 发送一个ajax请求
              axios.put("http://localhost:8088/admin/types/update/"+this.typeForm.id, this.typeForm).then(res => {
                console.log(res.data);
                if (res.data.code == 0) { //修改成功
                  this.$message({
                    message: '分类修改成功',
                    type: 'success',
                    offset:120,
                    showClose:true
                  });
                  // 阻塞0.3秒
                  setTimeout(function() {
                    _this.toBackList(); // 返回至列表
                  }, 300);
                } else { // 修改失败
                  this.$message({
                    message:res.data.message,
                    type: 'error',
                    offset:120,
                    showClose:true
                  });
                }
              });
            }
          } else {
            this.$message({
              message:"输入不能为空!",
              type: 'error',
              offset:120,
              showClose:true
            });
            return false;
          }
        });
      },
    },

    mounted() {
      // 点击编辑按钮时，获取传来的id值
      // console.log(this.$route.params.row);
      if (this.$route.params.row != null){
        this.typeForm = this.$route.params.row;
      }
    }
  };

  //组件2 typeList
  const typeList = {
    template:"#typeListTemplate",
    data(){
      return {
        tableData: [],
        total: 0,
        size: 6,
        pageNow: 1
      };
    },
    methods:{
      // 设置表头行的样式
      tableHeaderColor({row,column,rowIndex,columnIndex}){
        return 'background-color:#0aa;color:#fff;font-wight:500;font-size:20px;'
      },
      // 设置索引,还未实现！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
      indexMethod(index){
        return (this.pageNow-1) * this.size + index + 1;
      },
      // 发布按钮路由跳转
      toInputIndex(){
        this.$router.push({path:'/type_input'});
      },
      // 新增按钮路由跳转
      toCreateType(){
        this.$parent.touchClassA(); // 调用方法改变导航按钮样式
        this.toInputIndex(); // 跳转路由
      },
      // 编辑按钮
      handleEdit(index, row) {
        console.log(index, row);
        this.$parent.touchClassA(); // 调用方法改变导航按钮样式
        this.$router.push({ // 路由跳转并传参
          name:'typeInput',
          params:{
            row:row //分类信息
          }
        });
      },
      // 删除按钮
      handleDelete(index, row) {
        console.log(index, row);
        //发送axios请求处理删除
        axios.delete("http://localhost:8088/admin/types/delete/" + row.id).then(res => {
          if (res.data.code == 0) { // 删除成功
            this.$message({
              message: "删除成功",
              type: 'success',
              offset:120,
              showClose:true
            });
            this.findAllTableData(this.page,this.size);// 刷新数据
          } else {
            this.$message({
              message:res.data.message,
              type: 'error',
              offset:120,
              showClose:true
            });
          }
        });
      },
      // 用来处理每页显示记录发生变化的方法
      findSize(size) {
        // console.log(size);
        this.size = size;
        this.findAllTableData(this.page,size);
      },
      // 用来处理分页相关方法
      findPage(page) {
        // console.log(page)
        this.page = page;
        this.findAllTableData(page, this.size);
      },
      // 查询分类列表
      findAllTableData(page, size) {
        page = page ? page : this.pageNow,
        size = size ? size : this.size;
        axios.post("http://localhost:8088/admin/types/list",{
          pageNum:page,
          pageSize:size
        }).then(res => {
          this.tableData = res.data.data;
          this.total = res.data.total;
        });
      }
    },
    created() {
      this.findAllTableData();
    }
  };

  //创建路由对象
  const router = new VueRouter({
    routes:[
      { path:'/',redirect:'/type_list'},  // redirect: 用来当访问的是默认路由 "/" 时 跳转到指定的路由展示
      { path:'/type_list', name:'typeList', component:typeList},
      { path:'/type_input', name:'typeInput', component:typeInput},
    ]
  });

  // 创建事件总线对象
  // var eventBus=new Vue();

  // 创建vue对象
  const app = new Vue({
    el: '#types',
    data: {
      isClassA:false,
      isClassB:true,
      show: false,
      userForm:{
        id: -1,
        newUserName:"",
        newPassword:"",
        oldPassword:""
      },
      rules: {
        newUserName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ]
      }
    },
    methods:{
      // 点击改变
      touchClassA(){
        this.isClassA = true;
        this.isClassB = false;
      },
      touchClassB(){
        this.isClassA = false;
        this.isClassB = true;
      },
      // 获取当前用户信息
      getCurrentUser(){
        axios.get("http://localhost:8088/admin/user/info").then(res => {
          if (res.data.code == 0) { // 查询成功
            console.log(res.data.data);
            this.userForm.id = res.data.data.id;
            this.userForm.newUserName = res.data.data.username;
          }
        });
      },
      // 修改用户信息按钮，获取当前用户信息
      resetUserInfo(){
        this.show = !this.show;
        if(this.show == true){ // 显示修改表单时才赋值
          this.getCurrentUser();// 表单赋值
        } else {// 不显示修改表单时，重置表单信息
          this.$refs.userForm.resetFields(); // 表单重置
          this.getCurrentUser(); // 表单赋值
        }
      },
      // 提交表单
      submitUserForm(userForm){
        this.$refs[userForm].validate((valid) => {
          if (valid) {
            if (this.userForm.id != -1){ // id 不为-1 即系统有当前用户
              axios.put("http://localhost:8088/admin/user/update/" + this.userForm.id, this.userForm).then(res => {
                // console.log(res.data);
                if (res.data.code == 0) { //修改成功
                  this.$message({
                    message: '用户信息修改成功',
                    type: 'success',
                    offset:120,
                    showClose:true
                  });
                  // 阻塞0.3秒
                  setTimeout(function() {
                    window.location.assign("http://localhost:8088/admin/logout"); // 注销当前用户跳转至登录页面
                  }, 700);
                } else { // 添加失败
                  this.$message({
                    message:res.data.message,
                    type: 'error',
                    offset:120,
                    showClose:true
                  });
                }
              });
            }
          } else {
            this.$message({
              message: "当前输入的数据不合法!!!",
              type: 'error',
              offset:120,
              showClose:true
            });
            return false;
          }
        });
      },
      // 取消用户编辑
      getBack(userForm) {
        this.$refs[userForm].resetFields();
        this.show=false;
      },
    },
    router,//注册路由
  });
</script>

<script>
  // 注销
  $('.menu.toggle').click(function () {
    $('.m-item').toggleClass('m-mobile-hide');
  });

  $('.ui.dropdown').dropdown({
    on : 'hover'
  });

  // 运行时间统计
  function secondToDate(second) {
    if (!second) {
      return 0;
    }
    var time = new Array(0, 0, 0, 0, 0);
    if (second >= 365 * 24 * 3600) {
      time[0] = parseInt(second / (365 * 24 * 3600));
      second %= 365 * 24 * 3600;
    }
    if (second >= 24 * 3600) {
      time[1] = parseInt(second / (24 * 3600));
      second %= 24 * 3600;
    }
    if (second >= 3600) {
      time[2] = parseInt(second / 3600);
      second %= 3600;
    }
    if (second >= 60) {
      time[3] = parseInt(second / 60);
      second %= 60;
    }
    if (second > 0) {
      time[4] = second;
    }
    return time;
  }
  function setTime() {
    /*此处为网站的创建时间*/
    var create_time = Math.round(new Date(Date.UTC(2021, 3, 15, 15, 15, 15)).getTime() / 1000);
    var timestamp = Math.round((new Date().getTime() + 8 * 60 * 60 * 1000) / 1000);
    currentTime = secondToDate((timestamp - create_time));
    currentTimeHtml = currentTime[0] + '年' + currentTime[1] + '天'
            + currentTime[2] + '时' + currentTime[3] + '分' + currentTime[4]
            + '秒';
    document.getElementById("htmer_time").innerHTML = currentTimeHtml;
  }
  setInterval(setTime, 1000);
</script>

<style>
  /* 发布组件显示宽度、位置 */
  .input_index{
    width: 54%;
    margin-top: 130px;
  }
  /* 列表组件显示宽度、位置 */
  .list_index{
    width: 54%;
    margin-top: 70px;
  }
  .el-input-group__prepend{
    color: #00aaaa;
    font-weight: 700;
    border: 1px solid #00aaaa;
    background-color: rgb(255,255,255);
  }
  .page_index{
    background-color: rgb(242, 242, 242);
    padding-top: 10px;
    padding-bottom: 10px
  }

  button.btn-next{
    background-color: #00aaaa;
    border-right: #f2f2f2;
  }

  /* 背景图 */
  body {
    font-size: 15px;
    padding: 0;
    margin: 0;
    font-family: "微软雅黑","宋体",Arial;
    width: 100%;
    height: 100%;
    background: url(https://unsplash.it/1000/400?image=24) no-repeat top
    center fixed;
    background-size: cover;
  }
</style>




